package com.jiazhong.mingxing.project.bookstore.front.filter;

import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.front.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 验证用户是否登陆了，对于某些请求必须登陆后才能访问
 */
//@WebFilter("/shopping_cart/add")
@Slf4j
//@Component
public class IsLoginFilter extends HttpFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public IsLoginFilter() {
        log.info("验证登陆过滤器加载了");
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String uri = request.getRequestURI();
        log.info("uri:{}", uri);
        if (!uri.contains("/shopping_cart")) {
            chain.doFilter(request, response);
            return;
        }


        log.info("进入了验证用户是否登陆过滤器");
        // 1. 获取到你的token
        String token = request.getHeader("token");
        log.info("传递的token:{}", token);
        // 2. 校验有没有篡改
        boolean b = JwtConfig.checkToken(token);
        log.info("b:{}", b);
        if (!b) {
            // 3. token有问题或者没有传递
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JsonResult fail = ResultTool.fail("请登录后访问", 401);
            out.println(fail);
            return;
        }
        // 4. 没有篡改过，验证是否在redis中存在
        Object id = JwtConfig.parseJWT(token).get("id");
        String redisToken = stringRedisTemplate.opsForValue().get(UserServiceImpl.FRONT_TOKEN + id.toString());
        boolean equals = Objects.equals(redisToken, token);
        log.info("redisToken:{},是否一致:{}", redisToken, equals);
        if (!equals) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JsonResult fail = ResultTool.fail("请登录后访问", 401);
            out.println(fail);
            return;
        }
        log.info("用户是登陆状态");
        // 5. 用户是登陆的
        chain.doFilter(request, response);
    }
}
